# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
import os

from itemadapter import ItemAdapter
from pymongo import MongoClient


class TwoPipeline:
    def open_spider(self, spider):
        print('进入管道')
        client = MongoClient("127.0.0.1", 18001)
        self.collection = client["test2"]["news"]
        if not os.path.exists('./download'):  # 判断文件夹或文件
            os.makedirs('./download')

    def process_item(self, item, spider):
        types = item.get("type")
        if types == 'text':
            ret = self.collection.insert(item)
        elif types == "img":
            print('下载图片')
            with open('./download/' + item.get('title'), 'wb') as f:
                f.write(item.get('info'))
